/*
 * @Author: y001554
 * @Date: 2023-01-16 20:11:08
 * @LastEditors: y001554
 * @LastEditTime: 2023-02-12 15:44:53
 * @FilePath: \ylwl\packages\plugins\components\tree\src\composables\use-toggle.ts
 * @Description:
 *
 * Copyright (c) 2023 by FE/ylwl, A l Rights Reserved
 */
import { ref, reactive } from 'vue'
import { TreeData, TreeItem, CustomerProps } from '../types'

export default function useToggle(data: TreeData, prop: CustomerProps): any {
  //@备注:元素映射 数组
  //@取值:
  interface DataObj {
    [key: string]: Array<string>
  }

  //数组转数  区分是否过滤 open字段
  const openedTree = (tree: TreeData, filter: Boolean = true): TreeData => {
    if (filter) {
      const res: TreeData = tree.reduce(
        (acc: TreeData, item: TreeItem) =>
          item.open && item.children
            ? acc.concat(item, openedTree(item.children))
            : acc.concat(item),
        []
      )

      return res
    } else {
      return tree.reduce(
        (acc: TreeData, item: TreeItem) =>
          item.children
            ? acc.concat(item, openedTree(item.children, false))
            : acc.concat(item),
        []
      )
    }
  }

  // 扩展数据结构
  const filterTree = (
    tree: TreeData,
    pid: Array<string>,
    level: number
    // res: DataObj
  ): TreeData => {
    tree.map((item) => {
      const kvalue = item[prop.keyName || 'id' || 'value']
      item.pids = pid
      item.level = level
      if (item.children) {
        filterTree(item.children, [...pid, kvalue], level + 1)
      }
    })
    return tree
  }

  // 创建完成数据结构
  // const createTree = (tree: TreeData, filter: Boolean = true): DataObj => {
  //   let res: DataObj = {}

  //   const result = filterTree(tree, [], 1, res)
  //   return openedTree(result, filter)
  // }

  //计算所有元素的子集
  const calcSum = (tree: TreeData): DataObj => {
    const res: DataObj = {}
    const data = openedTree(tree, false)

    data.map((it: TreeItem) => {
      // console.log('tree', it.pids)
      const kvalue = it[prop.keyName || 'value']
      if (it.pids) {
        it.pids.map((item) => {
          // console.log(res[item + ''])
          // debugger
          if (res[item + '']) {
            res[item + ''].push(kvalue)
          } else {
            res[item + ''] = [kvalue + '']
          }
        })
      }
    })
    // console.log('data', res)
    return res
  }

  const expentData = filterTree(data, [], 1)
  const openedData = ref(openedTree(expentData)) // 响应式对象

  const subsDataObj = reactive(calcSum(data))
  // console.log('expentData', subsDataObj)
  // 触发打开状态
  const toggle = (item: TreeItem) => {
    if (!item.children) return
    // 如果设置禁止打开则跳过
    if (item.disableToggle) return
    item.open = !item.open

    openedData.value = openedTree(expentData)
  }

  return {
    openedData,
    toggle,
    subsDataObj
  }
}
